package io.renren.modules.app.controller;

import java.sql.Wrapper;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.renren.modules.app.annotation.Login;
import io.renren.modules.app.annotation.LoginUser;
import io.renren.modules.app.entity.ImApplyEntity;
import io.renren.modules.app.entity.SendInfo;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.service.ImApplyService;
import io.renren.modules.app.service.UserService;
import io.renren.modules.app.tio.TioServerConfig;
import io.renren.modules.app.tio.WsOnlineContext;
import io.renren.modules.app.utils.ChatUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.websocket.common.WsResponse;


/**
 *
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2020-04-22 14:16:37
 */
@RestController
@RequestMapping("app/imapply")
public class ImApplyController {
    @Autowired
    private ImApplyService imApplyService;
    @Autowired
    private UserService userService;

    /**
     * 列表
     */
    @Login
    @RequestMapping("/list")
    //@RequiresPermissions("generator:imapply:list")
    public R list(@LoginUser UserEntity user , @RequestParam Map<String, Object> params){
        params.put("friend_id",user.getUserId());
        PageUtils page = imApplyService.queryPage(params,user);
        int count = imApplyService.count(new QueryWrapper<ImApplyEntity>().eq("status", "pending").eq("friend_id", user.getUserId()));
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("page",page);
        map.put("count",count);
        return R.ok(map);
    }

    /**
     * 处理申请
     */
    @Login
    @RequestMapping("/handle")
    //@RequiresPermissions("generator:imapply:info")
    public R handle(@LoginUser UserEntity user,@RequestBody ImApplyEntity imApply) throws JsonProcessingException {
        //imApplyService.handle(imApply,user);

        return R.ok(imApplyService.handle(imApply,user));
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("generator:imapply:info")
    public R info(@PathVariable("id") Integer id){
		ImApplyEntity imApply = imApplyService.getById(id);

        return R.ok().put("imApply", imApply);
    }



    /**
     * 保存
     */
    @Login
    @RequestMapping("/save")
    //@RequiresPermissions("generator:imapply:save")
    public R save(@LoginUser UserEntity user,@RequestBody ImApplyEntity imApply) throws JsonProcessingException {
        if(user.getUserId().toString().equals(imApply.getFriendId().toString())){
            return R.error("不能添加自己");
        }
        UserEntity u = userService.getById(imApply.getFriendId());
        if(u==null){
            return R.error("该用户不存在或者已被禁用");
        }
        ImApplyEntity a = imApplyService.getOne(new QueryWrapper<ImApplyEntity>().eq("user_id", user.getUserId()).eq("friend_id", imApply.getFriendId()));
        if(a!=null){
            return R.error("你之前已经申请过了");
        }
        imApply.setCreatedAt(new Date());
        imApply.setUpdatedAt(new Date());
		imApplyService.save(imApply);

        //发送信息
        SendInfo sendInfo = new SendInfo();
        sendInfo.setCode(ChatUtils.MSG_MESSAGE);
        sendInfo.setMsg("updateApplyList");
        WsResponse wsResponse = WsResponse.fromText(new ObjectMapper().writeValueAsString(sendInfo), TioServerConfig.CHARSET);
        ChannelContext cco = WsOnlineContext.getChannelContextByUser(user.getUserId().toString());
        Tio.sendToUser(cco.groupContext, imApply.getFriendId().toString(), wsResponse);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("generator:imapply:update")
    public R update(@RequestBody ImApplyEntity imApply){
		imApplyService.updateById(imApply);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("generator:imapply:delete")
    public R delete(@RequestBody Integer[] ids){
		imApplyService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
